﻿using SharpSoft.Maths.MultipleObjectTracker;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;

namespace SharpSoft.Maths
{
    /// <summary>
    /// 平面坐标点的运动管理
    /// </summary>
    public class PointMotionManager : IDisposable
    {
        public PointMotionManager(float iouThreshold = 0.3f, int maxMisses = 3)
        {
            tracker = new SortTracker(iouThreshold, maxMisses);
        }
        readonly ITracker tracker;

        public event MotionPointEventHandler ActiveFrame;


        public void NewFrame(Vector2[] array)
        {
            IEnumerable<Track> tracks;
            if (array == null)
            {
                tracks = tracker.Track(new RectangleF[0]);
            }
            else
            {
                tracks = tracker.Track(toRectF(array));
            }
            List<Track> added = new List<Track>();
            List<Track> removed = new List<Track>();
            List<Track> moved = new List<Track>();


            foreach (var track in tracks)
            {
                switch (track.State)
                {
                    case TrackState.Started:
                        added.Add(track);
                        break;
                    case TrackState.Active:
                    case TrackState.Ending:
                        moved.Add(track);
                        break;
                    case TrackState.Ended:
                        removed.Add(track);
                        break;
                    default:
                        break;
                }
            }
            MotionPointEventArgs e = new MotionPointEventArgs()
            {
                Added = added.ToArray(),
                Moved = moved.ToArray(),
                Removed = removed.ToArray()

            };
            OnActiveFrame(e);
        }

        protected void OnActiveFrame(MotionPointEventArgs e)
        {
            ActiveFrame?.Invoke(this, e);
        }
        private RectangleF[] toRectF(IEnumerable<Vector2> v2s)
        {
            List<RectangleF> l = new List<RectangleF>();
            foreach (var item in v2s)
            {
                l.Add(new RectangleF(item.X, item.Y, 1, 1));
            }
            return l.ToArray();
        }
        public void Dispose()
        {

        }

    }

}
